﻿/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 3/1/2011
 * Time: 8:30 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using TomatoSynchronizer.Entities;
using TomatoSynchronizer.Store;
using HtmlAgilityPack;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace TomatoSynchronizer.Synchronizer
{
	/// <summary>
	/// Description of UnitClassSynchronizer
	/// </summary>
	public static class UnitClassSynchronizer
	{
		public static void Synchronize(Site siteSrc,Site siteDest,HtmlWeb client,SyncDirection direction)
		{
			switch(direction)
			{
				case SyncDirection.Download:
					UpLoadItems(siteDest,siteSrc,client,direction);
					break;
				case SyncDirection.Upload:
					UpLoadItems(siteSrc,siteDest,client,direction);
					break;
				case SyncDirection.DownloadAndUpload:
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					break;
				case SyncDirection.UploadAndDownload:
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					break;
				case SyncDirection.Synchronize:
					UnitClassStore UnitClassStoreDest = new UnitClassStore(siteDest,client);
					UnitClassStoreDest.Truncate();
					
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					
					var uclasses = UnitClassStoreDest.DownloadItems();
					
					foreach(UnitClass uclass in uclasses)
					{
						var rclass = UnitClassStoreDest.LoadItem(uclass.unit_class_id);
						
						if(rclass == null)
						{
							if(!UnitClassStoreDest.DeleteItem(uclass.unit_class_id))
							{
								throw new Exception("Could not delete the UnitClass " + uclass.unit_class_id + " in site " + UnitClassStoreDest.site.Name);
							}
						}
					}
					
					break;
			}
		}
		
		private static void UpLoadItems(Site _siteSrc,Site _siteDest,HtmlWeb client,SyncDirection direction)
		{
			UnitClassStore UnitClassStoreSrc = new UnitClassStore(_siteSrc,client);
			UnitClassStore UnitClassStoreDest = new UnitClassStore(_siteDest,client);
			
			UnitClass[] UnitClassesSrc =  UnitClassStoreSrc.LoadItems();
			UnitClass[] UnitClassesDest =  UnitClassStoreDest.LoadItems();
			
			MappingStore mappingStoreSrc = new MappingStore(_siteSrc,_siteDest,"unit_class_id");
			MappingStore mappingStoreDest = new MappingStore(_siteDest,_siteSrc,"unit_class_id");
			
			mappingStoreSrc.Clean<UnitClass>(UnitClassStoreSrc,UnitClassStoreDest);
			mappingStoreDest.Clean<UnitClass>(UnitClassStoreDest,UnitClassStoreSrc);
			
			MappingStore mappingStore = new MappingStore(_siteSrc,_siteDest,"languages_id");
			
			List<UnitClass> alreadySynchronized = new List<UnitClass>();
			
			foreach(UnitClass UnitClassSrc in UnitClassesSrc)
			{
				//we assume the UnitClass is not yet synchronized
				bool synchronized = false;
				
				//we check if a mapping already exists for this UnitClass in the destination store
				foreach(Mapping mapping in mappingStoreSrc.Mappings)
				{
					if(mapping.SrcValue == UnitClassSrc.unit_class_id && synchronized == false)
					{
						if(!string.IsNullOrEmpty(mapping.DestValue))
						{
							//this UnitClass already exists in the destination store
							//we check if everything changed since the last synchronization
							UnitClass UnitClassDest = UnitClassStoreDest.GetItem(mapping.DestValue);
							if(!string.IsNullOrEmpty(UnitClassDest.unit_class_id))
							{
								synchronized = SynchronizeItem(UnitClassSrc,UnitClassDest);
							}
							else
							{
								//the mapping exists, but the UnitClass has been deleted in the destination store
								//we set a flag that this mapping does not exists anymore
								mapping.Exists = false;
							}
						}
					}
				}
				
				if(!synchronized)
				{
					//there is no mapping, we check if this UnitClass already exists in the destination store
					foreach(UnitClass UnitClassDest in UnitClassesDest)
					{
						foreach(Mapping mapping in mappingStore.Mappings)
						{
							try
							{
								if(UnitClassSrc.unit_class_titles["unit_class_title[" + mapping.SrcValue + "]"] == UnitClassDest.unit_class_titles["unit_class_title[" + mapping.DestValue + "]"] && synchronized == false && !alreadySynchronized.Contains(UnitClassSrc))
								{
									//we get the 2 currencies from sites to get sure they really exist
									UnitClass src = UnitClassSrc.Store.GetItem(UnitClassSrc.unit_class_id);
									UnitClass dest = UnitClassDest.Store.GetItem(UnitClassDest.unit_class_id);
									
									if(!string.IsNullOrEmpty(src.unit_class_id))
									{
										if(!string.IsNullOrEmpty(dest.unit_class_id))
										{
											Mapping _mapping = new Mapping(UnitClassSrc.unit_class_id,UnitClassDest.unit_class_id,"unit_class_id");
											mappingStoreSrc.Mappings.Add(_mapping);
											
											synchronized = SynchronizeItem(UnitClassSrc,UnitClassDest);
										}
										else
										{
											synchronized = false;
										}
									}
									else
									{
										synchronized = true;
									}
								}
							}
							catch (KeyNotFoundException)
							{
								
							}
						}
						
					}
				}
				
				if(!synchronized)
				{
					//no mapping the UnitClass is new
					//we insert it in the destination store
					string remoteId = string.Empty;
					
					Dictionary<string, string> _titles = new Dictionary<string, string>();
					
					MappingStore _mappingStore = new MappingStore(UnitClassSrc.Store.site,UnitClassStoreDest.site,"languages_id");
					foreach(Mapping mapping in _mappingStore.Mappings)
					{
						_titles["unit_class_title[" + mapping.DestValue + "]"] = UnitClassSrc.unit_class_titles["unit_class_title[" + mapping.SrcValue + "]"];
					}
					
					
					var oldTitles = UnitClassSrc.unit_class_titles;
					
					UnitClassSrc.unit_class_titles = _titles;
					
					remoteId = UnitClassStoreDest.InsertItem(UnitClassSrc);
					
					synchronized = remoteId != string.Empty;
					
					if(!synchronized)
					{
						throw new Exception("The UnitClass " + UnitClassSrc.unit_class_id + " has not been synchronized");
					}
					
					UnitClassSrc.unit_class_titles = oldTitles;
					
					Mapping _mapping = new Mapping(UnitClassSrc.unit_class_id,remoteId,"unit_class_id");
					mappingStoreSrc.Mappings.Add(_mapping);
					synchronized = true;
				}
				
				if(!synchronized)
				{
					throw new Exception("could not synchronize the UnitClass " + UnitClassSrc.unit_class_id);
				}
				
				UnitClassStoreSrc.PersistItem(UnitClassSrc);
				alreadySynchronized.Add(UnitClassSrc);
			}
			
			mappingStoreSrc.Save();
			
			mappingStoreDest.Truncate();
			
			//we save the mappings in the destination MappingStore too
			foreach(Mapping mapping in mappingStoreSrc.Mappings)
			{
				if(mapping.Exists)
				{
					Mapping mappingDest = new Mapping(mapping.DestValue,mapping.SrcValue,mapping.Property);
					mappingStoreDest.Mappings.Add(mappingDest);
				}
			}
			
			mappingStoreDest.Save();						
			
			//we check if the 2 MappingStore are synchronized
			if(mappingStoreSrc.Mappings.Count != mappingStoreDest.Mappings.Count)
			{
				throw new Exception("The mapping store are not synchronized");
			}
		}
		
		private static bool SynchronizeItem(UnitClass UnitClassSrc,UnitClass UnitClassDest)
		{
			bool synchronized = true;
			
			if(!UnitClassSrc.Equals(UnitClassDest))
			{
				synchronized = false;
				
				//we update the destination UnitClass
				UnitClassSrc.language_id = UnitClassDest.language_id;
				UnitClassSrc.unit_class_id = UnitClassDest.unit_class_id;
				
				var languages = UnitClassDest.Store.site.GetLanguageStore().LoadItems();
				
				Dictionary<string, string> _titles = new Dictionary<string, string>();
				
				MappingStore mappingStore = new MappingStore(UnitClassSrc.Store.site,UnitClassDest.Store.site,"languages_id");
				foreach(Mapping mapping in mappingStore.Mappings)
				{
					_titles["unit_class_title[" + mapping.DestValue + "]"] = UnitClassSrc.unit_class_titles["unit_class_title[" + mapping.SrcValue + "]"];
				}
				
				
//				var oldTitles = UnitClassSrc.unit_class_titles;
				
				UnitClassSrc.unit_class_titles = _titles;
				
				synchronized = UnitClassDest.Store.UpdateItem(UnitClassSrc);
			}
			
			return synchronized;
		}
		
		private static string UploadItem(UnitClassStore UnitClassStoreDest,UnitClass UnitClass)
		{
			string remoteId = string.Empty;
			
			remoteId = UnitClassStoreDest.InsertItem(UnitClass);
			
			return remoteId;
		}
	}
}
